package com.shuany.ws.jaxb;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * 通过jaxb 进行  object 转xml， 或者xml转object
 * @author yushan
 * @version 1.0
 */
public class JAXBTest {

    public static void main(String[] args) {
        try {
            JAXBContext context = JAXBContext.newInstance(Person.class);
            
            //通过jaxb 将Object转换成xml
            Marshaller marshaller = context.createMarshaller();
            Person p = new Person("shan", "yu", 28, true, "man", 1.75d);
            Address address = new AddressImpl();
            address.setAddress("fujian xiamen");
            p.setAddress(address);
            //Person p = new Person();
            marshaller.marshal(p, System.out); //形成的xml，只会输出有带值的参数
            
            System.out.println("\n--------------");
            
            //通过jaxb 将xml转换成object;如果有值的就付给相应的属性，如果没有的基本类型采用默认值，其他则为null
            Unmarshaller unmarshaller = context.createUnmarshaller();
            //String xml = "<person><china>true</china><height>1.75</height><lastName>yu</lastName><sex>man</sex></person>";
            //其xml必须匹配
            String xml = "<ns2:TestPerson xmlns:ns2=\"http://www.shuanys.com\"><china>true</china><height>1.75</height><lastName>yu</lastName><sex>man</sex></ns2:TestPerson>";
            Person p2 = (Person)unmarshaller.unmarshal(new StringReader(xml));
           // System.out.println(p2.getLastName() + " " + p2.getFirstName() + " " + p2.getAge());
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
